package com.jcfk.system.config;

import com.jcfk.system.utils.mail.JavaMailUntil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import java.util.Properties;

/**
 * 构建发送邮箱配置类
 *
 * @author 李炳海
 */
@Configuration
public class EmailConfig implements CommandLineRunner {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${spring.mail.username}")
    private String username;

    @Value("${spring.mail.password}")
    private String password;

    @Value("${spring.mail.host}")
    private String host;


    @Override
    public void run(String... args) {
        // 创建一个配置文件，并保存
        Properties props = new Properties();
        try {

            // SMTP服务器连接信息
            // 126——smtp.126.com
            // 163——smtp.163.com
            // qqsmtp.qq.com"
            props.put("mail.smtp.host", host);//	SMTP主机名

            // 126——25
            // 163——645
            props.put("mail.smtp.port", "25");//	主机端口号
            props.put("mail.smtp.auth", "true");//	是否需要用户认证
            props.put("mail.smtp.starttls.enale", "true");//	启用TlS加密

            Session session = Session.getInstance(props, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    // TODO Auto-generated method stub
                    return new PasswordAuthentication(username, password);
                }
            });

            // 控制台打印调试信息
            session.setDebug(false);

            JavaMailUntil.setSession(session);
        } catch (Exception e) {
            logger.error("邮箱初始化失败", e);
        }

    }
}
